var router = require("../libs/router")
require("libjv");

const mor = require("../libs/mongoHelper")
const apiService = require("../libs/apiEval")
const {JsonResult} = require("../libs/JsonResult");

const curl = require("../libs/curl")

router.get('/', async (json, req, resp) => {
    return "ok";
});

router.post('/run-story', async (ctx) => {
    var json = ctx.queryJson;
    if (!json.storyId) {
        return JsonResult.error("找不到 storyId");
    }

    var story = await mor.findOne("apiStory", {_id: json.storyId});
    if (!story) {
        return JsonResult.error("找不到 story");
    }

    return await apiService.runStory(story);
});

router.post('/run-api', async (ctx) => {

    var json = ctx.queryJson;

    if (!json.storyId) {
        return JsonResult.error("找不到 storyId");
    }

    if (jv.isNull(json.apiIndex)) {
        return JsonResult.error("找不到 apiIndex");
    }


    var story = await mor.findOne("apiStory", {_id: json.storyId});
    if (!story) {
        return JsonResult.error("找不到 story");
    }

    if (json.apiIndex >= story.apis.length) {
        return JsonResult.error("apiIndex超出范围");
    }

    await apiService.runApi(story, json.apiIndex);


    return JsonResult.of()
});


router.post('/exec-curl', async (ctx) => {
    var curlText = ctx.postBody;

    return curl.exec(curlText);
});


router.post('/exec-api', async (ctx) => {
    var json = ctx.postJson;

    return await apiService.execOriApi(json.method, json.url, json.headers, json.postBody);
});


module.exports = router
